package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tan.model.domain.UserInfo;
import com.tan.model.mongo.Video;
import com.tan.model.mongo.VideoComment;
import com.tan.model.vo.PageResult;
import com.tan.model.vo.VideoCommentVo;
import com.tan.model.vo.VideoVo;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.FocusUserApi;
import com.tanhua.dubbo.api.UserInfoapi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.dubbo.api.VideocommentApi;
import com.tanhua.server.interceptor.Userthread;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {
    @Autowired
    OssTemplate ossTemplate;
    @DubboReference
    VideoApi videoApi;
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @DubboReference
    UserInfoapi userInfoapi;
    @DubboReference
    FocusUserApi focusUserApi;
    @DubboReference
    VideocommentApi videocommentApi;
    //文件的上传下载
    @Autowired
    private FastFileStorageClient client;
    @Autowired
    FdfsWebServer webService;
    public void saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
      Long userid=  Userthread.getUser().getId();
      String name=  videoThumbnail.getOriginalFilename();
      InputStream inputStream = videoThumbnail.getInputStream();
      String imageUrl =  ossTemplate.uploadFile(name,inputStream);
        InputStream inputStream2 = videoFile.getInputStream();
        String fileName = videoFile.getOriginalFilename();
        fileName=fileName.substring(fileName.lastIndexOf(".")+1);
        StorePath storePath = client.uploadFile(inputStream2,videoFile.getSize(),fileName,null);
        String videoUrl= webService.getWebServerUrl()+storePath.getFullPath();
       videoApi.saveVideo(imageUrl,videoUrl,userid);

    }
    @Cacheable(value = "videos", key = "T(com.tanhua.server.interceptor.Userthread).getUser()?.id + '_' + #page + '_' + #pagesize")

    public PageResult queryVideoList(Integer page, Integer pagesize) {
        Long userid=  Userthread.getUser().getId();
      String vid = redisTemplate.opsForValue().get(Constants.VIDEOS_RECOMMEND+userid);
      List<VideoVo> listVo = new ArrayList<>();
      if(vid != null &&!vid.isEmpty()){
         String[] split = vid.split(",");
       if((page-1)*pagesize<split.length){
           List<Long> vids = Arrays.stream(split).skip((page-1)*pagesize)
                   .limit(pagesize).
                   map(Long::parseLong).collect(Collectors.toList());
           List<Video> list = videoApi.queryVideoList(vids);
           for (Video video : list) {
               Long videouserid= video.getUserId();
               UserInfo userInfo = userInfoapi.getUserInfo(videouserid);
               VideoVo videoVo = VideoVo.init(userInfo, video);
               if(  redisTemplate.opsForHash().hasKey(Constants.VIDEO_LIKE + video.getId(),Constants.VIDEO_LIKE +Userthread.getUser().getId())){
                   videoVo.setHasLiked(1);
               }
             //加入判断是否关注
               if(redisTemplate.opsForHash().hasKey(Constants.USER_FOCUS + Userthread.getUser().getId(),Constants.USER_FOCUSED +video.getUserId()))
               {
                   videoVo.setHasFocus(1);
               }
               listVo.add(videoVo);
           }
       }

      }else{
          List<Video> list = videoApi.queryVideoListnotvid(page,pagesize);
          for (Video video : list) {
              Long videouserid= video.getUserId();
              UserInfo userInfo = userInfoapi.getUserInfo(videouserid);
              VideoVo videoVo = VideoVo.init(userInfo, video);
              if(  redisTemplate.opsForHash().hasKey(Constants.VIDEO_LIKE + video.getId(),Constants.VIDEO_LIKE +Userthread.getUser().getId())){
                  videoVo.setHasLiked(1);
              }
              //加入判断是否关注
              if(redisTemplate.opsForHash().hasKey(Constants.USER_FOCUS + Userthread.getUser().getId(),Constants.USER_FOCUSED +video.getUserId()))
              {
                  videoVo.setHasFocus(1);
              }
              listVo.add(videoVo);
          }
      }
    return new PageResult(page,pagesize,listVo.size(),listVo);






    }

    public void likeVideo(String id) {
        String key = Constants.VIDEO_LIKE + id;
        String hashkey=Constants.VIDEO_LIKE + Userthread.getUser().getId();
        redisTemplate.opsForHash().put(key,hashkey,"1");
        videoApi.likeVideo(id);
    }

    public void dislikeVideo(String id) {
        String key = Constants.VIDEO_LIKE + id;
        String hashkey=Constants.VIDEO_LIKE + Userthread.getUser().getId();
        redisTemplate.opsForHash().delete(key,hashkey);


        videoApi.dislikeVideo(id);
    }

    public void saveVideoComments(String videoid, String comment) {
       Long userid= Userthread.getUser().getId();
       videocommentApi.saveVideoComments(videoid,comment,userid);
    }

    public PageResult queryVideoComments(String videoid, Integer page, Integer pagesize) {
    List<VideoComment> list = videocommentApi.queryVideoComments(videoid,page,pagesize);
    List<VideoCommentVo>videoCommentVoList= new ArrayList<>();
      for (VideoComment videoComment : list) {
          Long userid = videoComment.getUserId();
          UserInfo userInfo = userInfoapi.getUserInfo(userid);
          VideoCommentVo videoCommentVo = VideoCommentVo.init(userInfo, videoComment);
        if(  redisTemplate.opsForHash().hasKey(Constants.VIDEO_COMMENT_LIKE + videoComment.getId(),Constants.VIDEO_COMMENT_LIKE +Userthread.getUser().getId()))
        {
            videoCommentVo.setHasLiked(1);
        }
          videoCommentVoList.add(videoCommentVo);

      }
    return new PageResult(1,10,videoCommentVoList.size(),videoCommentVoList);




    }

    public void likeVideoComments(String id) {
        String key = Constants.VIDEO_COMMENT_LIKE + id;
        String hashkey=Constants.VIDEO_COMMENT_LIKE + Userthread.getUser().getId();
        redisTemplate.opsForHash().put(key,hashkey,"1");
        videocommentApi.likeVideoComments(id);

    }

    public void dislikeVideoComments(String id) {
        String key = Constants.VIDEO_COMMENT_LIKE + id;
        redisTemplate.opsForHash().delete(key,Constants.VIDEO_COMMENT_LIKE + Userthread.getUser().getId());
        videocommentApi.dislikeVideoComments(id);

    }

    public void userFocus(Long focusid) {
        Long userid= Userthread.getUser().getId();
        String key = Constants.USER_FOCUS + userid;
        String hashkey=Constants.USER_FOCUSED + focusid;
        redisTemplate.opsForHash().put(key,hashkey,"1");
        focusUserApi.save(userid,focusid);

    }

    public void userUnFocus(Long disfocusid) {
        Long userid= Userthread.getUser().getId();
        String key = Constants.USER_FOCUS + userid;
        String hashkey=Constants.USER_FOCUSED + disfocusid;
        redisTemplate.opsForHash().delete(key,hashkey);
        focusUserApi.delete(userid,disfocusid);

    }
}
